<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationBarTitleText: '登录',
    enablePullDownRefresh: false,
  },
}
</route>
<template>
  <view>
    <view class="flex flex-col items-center mt-[220rpx]">
      <image src="/static/logo_long.png" class="w-[281rpx] h-[78rpx]" mode="aspectFill"></image>
      <image
        src="/static/title_long.png"
        class="w-[390rpx] h-[60rpx] mt-4"
        mode="aspectFill"
      ></image>

      <view class="mt-[236rpx] w-9/10">
        <!--  open-type="getPhoneNumber" @getphonenumber="handleGetPhone" @click="handleLogin"-->
        <wd-button
          :disabled="!state.isAgreement"
          :loading="state.disabled"
          :round="false"
          :block="true"
          custom-class="w-full"
          open-type="getPhoneNumber"
          @getphonenumber="handleGetPhone"
        >
          授权登录
        </wd-button>
      </view>
    </view>
    <view class="w-full fixed bottom-10 flex justify-center">
      <agreement v-model="state.isAgreement" />
    </view>
  </view>
</template>

<script setup>
import useUserStore from '@/store/user'
import { showLoading, showToast } from '@/utils/uni'
import { to } from '@/utils/navigation'
import { fetchAuthLogin, bindSuperiors, fetchQuickLogin, fetchOpenid } from '@/service/user'
const userStore = useUserStore()

const state = ref({
  disabled: false,
  isAgreement: false,
})

function getCode() {
  return new Promise((resolve) => {
    uni.login({
      success: (res) => {
        resolve(res.code)
      },
    })
  })
}

async function handleLoginSuccess(res) {
  const { token, showDialog, dialog_text } = res.data
  userStore.updateWelcomeConfig({
    showDialog,
    ...dialog_text,
  })
  await userStore.updateToken(token)
  await userStore.getUserInfo()
  if (userStore.shareCode) {
    bindSuperiors({
      code: userStore.shareCode,
    })
      .then(() => {
        userStore.setShareCode('')
      })
      .catch(() => {
        userStore.setShareCode('')
      })
  }

  showToast('登录成功', () => to('pages/index/index'))
}

async function handleGetPhone(e) {
  try {
    state.value.disabled = true
    const code = await getCode()
    const res = await fetchQuickLogin({
      openCode: code,
      mobileCode: e.code,
    })
    handleLoginSuccess(res)
  } finally {
    state.value.disabled = false
  }
}

async function handleLogin() {
  // #ifdef H5
  userStore.login({
    account: '13666666666',
    password: 'aa123123',
    scene: 1,
    terminal: 3,
  })
  showToast('登录成功', () => to('pages/index/index'))
  // #endif

  // #ifdef MP-WEIXIN
  try {
    const code = await getCode()
    const res = await fetchAuthLogin({
      code,
    })

    // handleLoginSuccess(res)
    // console.log(code, '????', res)
  } catch (err) {
    console.log(err)
  }
  // #endif
}
</script>

<style lang="scss" scoped></style>
